package com.leyou.user.controller;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;


/**
 * @Author: SGS
 * @Date : 2020/11/30 18:12
 * @Version :
 */
@RestController
@RequestMapping("info")
public class UserServiceController {


    private UserService userService;


    public UserServiceController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data") String data
            ,@PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.exists(data,type));
    }


    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result,
                                         @RequestParam("code") String code){
        if (result.hasErrors()){
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400,msg);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(
            @RequestParam("username")String username,
            @RequestParam("password")String password){
        return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username,password));
    }
}
